<script setup lang="ts">
import {useTimeRangeStore, useWeatherStore, useUserStore} from '@/store';
import {latStrFilter, lonStrFilter} from 'common/src/utils/lnglat';
import StartSvg from 'common/src/assets/imgs/start.svg?component';
import PauseSvg from 'common/src/assets/imgs/pause.svg?component';
import {
  getCustomUTCTimeFormat,
  getOffsetCloseTo3Hours,
  oneDay,
  filterLTOffsetCustom,
  getCustomLocalTimeFormat
} from 'common/src/utils/time';
import ColorLegend from './ColorLegend.vue';
import DataSourceSwitch from "@/pages/home/bottom/DataSourceSwitch.vue";
import {ElSwitch} from 'element-plus';

const weatherStore = useWeatherStore();
const timeRangeStore = useTimeRangeStore();
const userStore = useUserStore();
const progressContainerRef = ref<HTMLDivElement>();
const containerWidth = ref(0);
const showHoverTime = ref(false);
const hoverOffset = ref(0);
const hoverPosition = ref(0);
const lonlat = reactive({lon: 0, lat: -100});

const featherActive = computed({
  get() {
    return weatherStore.featherActive;
  },
  set(value) {
    if (value) {
      weatherStore.updateFeatherLayer();
    } else {
      weatherStore.hideFeatherLayer();
    }
  },
});

const particleActive = computed({
  get() {
    return weatherStore.particleActive;
  },
  set(value) {
    if (value) {
      weatherStore.updateParticleLayer();
    } else {
      weatherStore.hideParticleLayer();
    }
  },
});

const waveDirActive = computed({
  get() {
    return weatherStore.waveDirActive;
  },
  set(value) {
    if (value) {
      weatherStore.updateWaveDirLayer();
    } else {
      weatherStore.hideWaveDirLayer();
    }
  },
});

const dateArr = computed(() => {
  const dateLength = timeRangeStore.totalTime / oneDay;
  return new Array(dateLength).fill(1).map((_, index) => {
    // return filterDMMMZ(timeRangeStore.start + oneDay * index);
    return getCustomLocalTimeFormat(timeRangeStore.start + oneDay * index, 'MM-DD');
  });
});

const dateFrequency = computed(() => {
  const itemWidth = containerWidth.value / dateArr.value.length;
  const minItemWidth = 50;
  return Math.ceil(minItemWidth / itemWidth);
});

const progressClick = (event: MouseEvent) => {
  const width = (event.currentTarget as HTMLDivElement).offsetWidth;
  const position = event.offsetX;
  timeRangeStore.updateOffset(Math.floor((position / width) * timeRangeStore.totalTime));
};

const progressMousemove = (event: MouseEvent) => {
  const width = (event.currentTarget as HTMLDivElement).offsetWidth;
  const position = event.offsetX;
  // props.update(position / width * (props.end - props.start));
  hoverPosition.value = (position / width) * timeRangeStore.totalTime;
  hoverOffset.value = Math.floor(timeRangeStore.start + (position / width) * timeRangeStore.totalTime) - timeRangeStore.start;
};

const handleResize = () => {
  containerWidth.value = progressContainerRef.value!.clientWidth;
};

watch(() => weatherStore.map, () => {
  if (weatherStore.map) {
    weatherStore.map.on('mousemove', (e) => {
      lonlat.lon = e.lngLat.lng;
      lonlat.lat = e.lngLat.lat;
    });
  }
});

onMounted(() => {
  handleResize();
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
</script>

<template>
  <div class="bottom-container">
    <div class="bottom-left-container">
      <div class="time-operation">
        <StartSvg v-if="!timeRangeStore.playing" @click="() => timeRangeStore.startPlaying()"/>
        <PauseSvg v-show="timeRangeStore.playing" @click="() => timeRangeStore.stopPlaying()"/>
      </div>
      <div ref="progressContainerRef" class="progress-container">
        <div
            v-for="(item, idx) in dateArr"
            :key="`${item}${idx}`"
            :class="['date-block', {'date-block-start': idx === 0, 'date-block-end': idx === dateArr.length - 1}]"
            :style="{width: `${100 / dateArr.length}%`}"
        >
          <span class="date-line"></span>
          <span class="date-text" v-show="idx % dateFrequency === 0">{{ item }}</span>
        </div>
        <div class="active-area" key="active-area"
             :style="{width: `${timeRangeStore.offset / timeRangeStore.totalTime * 100}%`}"></div>
        <div class="active-text" key="active-text"
             :style="{left: `${timeRangeStore.offset / timeRangeStore.totalTime * 100}%`}">
          <div>{{ filterLTOffsetCustom(timeRangeStore.currentTime, timeRangeStore.timeZone, 'MM-DD/HHmm') }}</div>
          <div>{{ getCustomUTCTimeFormat(timeRangeStore.currentTime, 'MM-DD/HHmm[Z]') }}</div>
        </div>
        <div
            class="hover-area"
            key="hover-area"
            @click="(e) => progressClick(e)"
            @mousemove="(e) => progressMousemove(e)"
            @mouseenter="showHoverTime = true"
            @mouseleave="showHoverTime = false"
        ></div>
        <div v-show="showHoverTime" class="hover-text" key="hover-text"
             :style="{left: `${hoverPosition / timeRangeStore.totalTime * 100}%`}">
          <div>{{
              filterLTOffsetCustom(timeRangeStore.start + hoverOffset, timeRangeStore.timeZone, 'MM-DD/HHmm')
            }}
          </div>
          <div>{{ getCustomUTCTimeFormat(timeRangeStore.start + hoverOffset, 'MM-DD/HHmm[Z]') }}</div>
        </div>
      </div>
      <div class="progress-intervel-config">
        <div class="progress-intervel-set">{{ timeRangeStore.speed.toFixed(1) }}X</div>
        <div class="progress-intervel-options">
          <span v-for="option in [4, 2, 1]" :key="option" class="progress-intervel-option"
                @click="() => timeRangeStore.speed = option">
            {{ option.toFixed(1) }}X
          </span>
        </div>
      </div>
    </div>
    <div class="bottom-right">
      <div class="bottom-switches">
        <ElSwitch
            v-model="featherActive"
            :disabled="weatherStore.climateLayerActive || userStore.taskPhase === 1 || weatherStore.mapMode === 'globe'"
            class="custom-switch"
            inline-prompt
            active-text="风羽"
            inactive-text="风羽"
            width="64px"
        />
        <ElSwitch
            v-model="particleActive"
            :disabled="weatherStore.climateLayerActive || userStore.taskPhase === 1 || weatherStore.mapMode === 'globe'"
            class="custom-switch"
            inline-prompt
            active-text="风粒子"
            inactive-text="风粒子"
            width="64px"
        />
        <ElSwitch
            v-model="waveDirActive"
            :disabled="weatherStore.climateLayerActive || userStore.taskPhase === 1 || weatherStore.mapMode === 'globe'"
            class="custom-switch"
            inline-prompt
            active-text="浪方向"
            inactive-text="浪方向"
            width="64px"
        />
      </div>
      <ColorLegend/>
      <DataSourceSwitch
          v-if="false"
          :options="[
    { value: 'cma', label: '中国气象局' },
    { value: 'ec', label: '欧洲气象中心' },
    { value: 'plan', label: '海二代' }
  ]"
      />
      <div class="bottom-lonlat" :style="{'background-color': lonlat.lat > -90 ? 'rgba(26, 26, 26, 0.6)' : 'transparent'}">
        <span v-show="lonlat.lat > -90">{{ latStrFilter(lonlat.lat) }}, </span>
        <span v-show="lonlat.lat > -90">{{ lonStrFilter(lonlat.lon) }}</span>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.bottom-container {
  position: absolute;
  bottom: 24px;
  display: flex;
  align-items: flex-end;
  left: 50px;
  right: 10px;
  z-index: 10;
  pointer-events: none;

  .bottom-left-container {
    display: flex;
    flex: 1;
    align-items: center;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
  }

  .bottom-right {
    align-self: flex-end;
    margin-left: 20px;
    display: flex;
    flex-flow: column nowrap;
    align-items: flex-start;

    & > *:not(:last-child) {
      margin-bottom: 10px;
    }
  }

  .bottom-lonlat {
    margin-top: 6px;
    margin-right: 110px;
    height: 24px;
    display: flex;
    align-items: center;
    padding: 0 4px;
    color: #fff;
    width: 180px;
    font-size: 12px;
    font-weight: 600;

    & > span {
      flex: 1;
    }
  }

  .time-operation {
    pointer-events: visiblePainted;
    position: relative;
    height: 50px;
    width: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    margin-right: 12px;
    // padding: 0 16px;
    // &>*:not(:first-child) {
    //   margin-left: 14px;
    // }
    :is(svg) {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      cursor: pointer;
      width: 66px;
      height: 66px;
    }
  }

  .progress-container {
    position: relative;
    // width: calc(100vw - 520px);
    height: 32px;
    flex: 1;
    display: flex;

    .hover-area {
      pointer-events: visiblePainted;
      position: absolute;
      z-index: 3;
      width: 100%;
      height: 8px;
      left: 0;
      top: 0;
      cursor: pointer;
    }

    .active-area {
      position: absolute;
      z-index: 2;
      height: 8px;
      left: 0;
      top: 0;
      background: linear-gradient(270deg, rgba(24, 144, 255, 0.395) 0%, #1E93FF 100%);
      border-radius: 4px 4px 4px 4px;
    }

    .active-text,
    .hover-text {
      position: absolute;
      top: -6px;
      padding: 4px 8px;
      font-size: 12px;
      border-radius: 6px;
      pointer-events: none;
      transform: translate(-50%, -100%);
      white-space: nowrap;
      text-align: center;

      &::after {
        content: ' ';
        position: absolute;
        bottom: -4px;
        left: 50%;
        transform: translateX(-50%);
        border-top: 6px solid #1E3049;
        border-left: 6px solid transparent;
        border-right: 6px solid transparent;
      }
    }

    .active-text {
      background-color: #1E3049;
      color: #fff;
    }

    .hover-text {
      background-color: #304b71;
      color: #f0f9eb;

      &::after {
        border-top-color: #304b71;
      }
    }
  }

  .progress-intervel-config {
    pointer-events: visiblePainted;
    position: relative;
    margin-left: 10px;
    font-size: 12px;
    color: #fff;
    width: 30px;
    text-align: center;
    cursor: pointer;

    &:hover {
      .progress-intervel-options {
        display: flex;
      }
    }

    .progress-intervel-set {
      background-color: rgba(30, 48, 73, 0.8);
      width: 100%;
    }

    .progress-intervel-options {
      display: none;
      flex-direction: column;
      position: absolute;
      bottom: 100%;
      left: 0;
      right: 0;
    }

    .progress-intervel-option {
      background-color: rgba(30, 48, 73, 0.6);

      &:hover {
        background-color: rgba(30, 48, 73, 0.8);
      }
    }
  }

  .date-block {
    position: relative;
    z-index: 2;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    font-size: 12px;
    color: #FFFFFF;
    line-height: 12px;
    box-sizing: border-box;
    white-space: nowrap;

    .date-line {
       border-left: 1px solid rgba(255,255,255,0.8);
      height: 8px;
      background-color: #1E3049;
    }

    .date-text {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      padding-left: 2px;
      line-height: 17px;
      text-shadow: 0px 1px 4px rgba(0, 0, 0, 0.4);
      font-weight: 500;
    }
  }

  .date-block-start {
    .date-line {
      border-top-left-radius: 5px;
      border-bottom-left-radius: 5px;
    }
  }

  .date-block-end {
    .date-line {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }

  .bottom-switches {
    margin-left: 110px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;

    & > *:not(:last-child) {
      margin-bottom: 10px;
    }
  }
}
</style>

<style lang="less">
.bottom-switches {
  .custom-switch {
    --el-switch-on-color: #1F93FF;
    --el-switch-off-color: linear-gradient(189deg, #3B5A7E 0%, #16253B 100%);
    height: unset;
    pointer-events: visiblePainted;

    .el-switch__core {
      box-shadow: 0px 2px 12px 0px rgba(0, 0, 0, 0.2);

      .el-switch__inner {
        .is-text {
          color: #ccc;
        }
      }

      .el-switch__action {
        left: 3px;
      }
    }

    &.is-checked .el-switch__core {
      background: var(--el-switch-on-color);

      .el-switch__inner {
        .is-text {
          color: #fff;
        }
      }

      .el-switch__action {
        left: calc(100% - 17px);
      }
    }
  }
}
</style>
